﻿using Microsoft.AspNetCore.Http;
using Serilog;
using SqlSugar;

namespace AME.WebAppCore
{
    public class RequestLoggingMiddleware
    {
        private readonly RequestDelegate _next;

        public RequestLoggingMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            // 记录请求信息
            var request = context.Request;
            Log.Information($"Request: {request.Method} {request.Path}");

            // 调用下一个中间件
            await _next(context);

            // 记录响应信息
            var response = context.Response;

            //如果响应码不是成功状态码（非 2xx）
            if (response.StatusCode < 200 || response.StatusCode >= 300)
            {
                // 记录请求信息
                Log.Information("Non-success HTTP Request Information:");
                Log.Information("Scheme: {Scheme}", context.Request.Scheme);
                Log.Information("Host: {Host}", context.Request.Host);
                Log.Information("Path: {Path}", context.Request.Path);
                Log.Information("QueryString: {QueryString}", context.Request.QueryString);
                Log.Information("Headers: {Headers}", context.Request.Headers);
            }
            Log.Information($"Response: {response.StatusCode}");
        }
    }
}

